package parser;

import java.io.Reader;

import ast.ExpressionNode;

/**
 * Implementation of {@link Parser}
 * 
 * @author Royce Feng (ryf2)
 *
 */
public class Parser {

	public static final String DEFAULT_UNIT = "anonymous_unit";
	private ExpressionParser parser;

	public Parser(Reader reader) {
		this(reader, DEFAULT_UNIT);
	}

	public Parser(Reader reader, String unit) {
		parser = new ExpressionParser(reader, unit);
	}

	public ExpressionNode parse() throws ParseException {
		try {
			Object obj = parser.parse().value;
			if (obj instanceof ExpressionNode) return (ExpressionNode) obj;
			else throw new ParseException("Unexpected result: Returned Symbol not of type AbstractSyntaxTree", parser.getCurrentToken().position());
		} catch (Exception e) {
			throw new ParseException(
					String.format("Syntax error at %s, position: %s", parser.getCurrentToken().value(), parser.getCurrentToken().position()),
					parser.getCurrentToken().position());
		}
	}

}
